package com.booksystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.booksystem.common.RestResult;
import com.booksystem.dto.ApproveReviewDTO;
import com.booksystem.dto.GetReviewsDTO;
import com.booksystem.dto.SubmitReviewDTO;
import com.booksystem.entity.OrderItemDO;
import com.booksystem.entity.ProductInfoDO;
import com.booksystem.entity.ProductReviewDO;
import com.booksystem.exception.BusinessException;
import com.booksystem.mapper.OrderItemMapper;
import com.booksystem.mapper.ProductInfoMapper;
import com.booksystem.mapper.ProductReviewMapper;
import com.booksystem.service.ProductReviewService;
import com.booksystem.utils.ResultCodeConstant;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *   商品评价服务实现类
 * </p>
 * @author 段伟豪
 */
@Slf4j
@Service
public class ProductReviewServiceImpl implements ProductReviewService {

    @Autowired
    private ProductReviewMapper productReviewMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Override
    @Transactional
    public RestResult<Boolean> submitReview(SubmitReviewDTO submitReviewDTO) {
        // 校验商品是否存在且已购买
        checkProductAndOrder(submitReviewDTO.getProductId(), submitReviewDTO.getUserId());

        // 构造评价对象
        ProductReviewDO productReviewDO = new ProductReviewDO();
        productReviewDO.setProductId(submitReviewDTO.getProductId());
        productReviewDO.setUserId(submitReviewDTO.getUserId());
        productReviewDO.setRating(submitReviewDTO.getRating());
        productReviewDO.setContent(submitReviewDTO.getContent());
        if (submitReviewDTO.getImages() != null && !submitReviewDTO.getImages().isEmpty()) {
            productReviewDO.setImages(String.join(",", submitReviewDTO.getImages()));
        }
        productReviewDO.setIsApproved((byte) 0); // 初始状态为待审核
        productReviewDO.setCreateBy("system");
        productReviewDO.setUpdateBy("system");

        // 保存评价信息到数据库
        int result = productReviewMapper.insert(productReviewDO);
        if (result > 0) {
            return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, true);
        } else {
            throw new BusinessException(ResultCodeConstant.CODE_000002, ResultCodeConstant.CODE_000002_MSG);
        }
    }

    @Override
    public RestResult<List<ProductReviewDO>> getReviews(GetReviewsDTO getReviewsDTO) {
        // 计算偏移量
        int offset = (getReviewsDTO.getPageNo() - 1) * getReviewsDTO.getPageSize();

        // 查询指定商品的评价信息并按时间倒序排列
        List<ProductReviewDO> reviews = productReviewMapper.selectReviewsByProductId(
                getReviewsDTO.getProductId(),
                offset,
                getReviewsDTO.getPageSize()
        );

        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, reviews);
    }

    @Override
    @Transactional
    public RestResult<Boolean> approveReview(ApproveReviewDTO approveReviewDTO) {
        // 判断评价是否存在
        ProductReviewDO review = productReviewMapper.selectById(approveReviewDTO.getReviewId());
        if (review == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG, false);
        }

        // 更新评价状态为审核通过或拒绝
        review.setIsApproved(approveReviewDTO.getIsApproved() ? (byte) 1 : (byte) 0);
        review.setUpdateBy("system");
        int result = productReviewMapper.updateById(review);
        if (result > 0) {
            return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, true);
        } else {
            throw new BusinessException(ResultCodeConstant.CODE_000002, ResultCodeConstant.CODE_000002_MSG);
        }
    }

    /**
     * 校验商品是否存在且已购买
     * @param productId 商品ID
     * @param userId 用户ID
     */
    private void checkProductAndOrder(Long productId, Long userId) {
        // 校验商品是否存在
        QueryWrapper<ProductInfoDO> productQuery = new QueryWrapper<>();
        productQuery.eq("product_id", productId).eq("is_on_sale", 1);
        ProductInfoDO product = productInfoMapper.selectOne(productQuery);
        if (product == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "商品不存在或未上架");
        }

        // 校验用户是否已购买该商品
        QueryWrapper<OrderItemDO> orderQuery = new QueryWrapper<>();
        orderQuery.eq("product_id", productId).eq("user_id", userId);
        OrderItemDO orderItem = orderItemMapper.selectOne(orderQuery);
        if (orderItem == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "商品不存在或未购买该商品");
        }
    }
}